
nmi:
	php
	pha
	txa
	pha
	tya
	pha

; keep this disabled... it fucks up any forced blanks
;	poke PPU_MASK, $fE

	lda FORCED_BLANK
	beq +
	jmp nmi_end
+


IFDEF vblank
	jsr vblank
ENDIF


	ldx #0
	stx PPU_OAM_ADDR
	lda #>OAM_BUF
	sta PPU_OAM_DMA

; copy palette to ppu
	lda #$3f
	sta PPU_ADDR
	stx PPU_ADDR
	i=0
	.rept 4
		;ldy PAL_BUF+i
		;lda (PAL_PTR),y
		lda PAL_BUF+i
		sta PPU_DATA
		i=i+1
	.endr
	j=0
	.rept 7
		lda PPU_DATA			;skip background color
		i=1
		.rept 3
			;ldy PAL_BUF+5+(j*4)+i
			;lda (PAL_PTR),y
			lda PAL_BUF+4+(j*4)+i
			sta PPU_DATA
			i=i+1
		.endr
		j=j+1
	.endr

	lda #0
	sta PPU_ADDR
	sta PPU_ADDR
	lda <SCROLL_X
	sta PPU_SCROLL
	lda <SCROLL_Y
	sta PPU_SCROLL

	inc <FRAMES ; do not comment out or remove - game will not start


; restore prg bank if necessary
; 	 ldx CURRENT_BANK
;   lda banktable, x      ; read a byte from the banktable
;   sta banktable, x      ; and write it back, switching banks

nmi_end:
	pla
	tay
	pla
	tax
	pla
	plp
irq:
	rti

; Controller Polling
; A, B, Select, Start, Up, Down, Left, Right
PAD_A=$01
PAD_B=$02
PAD_SEL=$04
PAD_START=$08
PAD_UP=$10
PAD_DOWN=$20
PAD_LEFT=$40
PAD_RIGHT=$80

;unsigned char __fastcall__ pad_poll(unsigned char pad);

	PAD_BUF=TEMP+1

poll_pad:
	tay
	ldx #0
	lda <PAD_STATE,y
	sta <PAD_STATEL,y


@padPollPort:
	lda #1
	sta CTRL_PORT1
	lda #0
	sta CTRL_PORT1
	lda #8
	sta <TEMP+1

@padPollLoop:
	lda CTRL_PORT1,y
	lsr a
	ror <PAD_BUF,x
	dec <TEMP+1
	bne @padPollLoop

	inx
	cpx #3
	bne @padPollPort

	lda <PAD_BUF
	cmp <PAD_BUF+1
	beq @done
	cmp <PAD_BUF+2
	beq @done
	lda <PAD_BUF+1
@done:
	sta <PAD_STATE,y


	rts




; =============== ~~~ ENTRY POINT ~~~ ===================
start:
    sei
    ldx #$ff
    txs
    inx
    stx PPU_MASK
    stx DMC_FREQ
    stx PPU_CTRL		;no NMI

waitSync1:
    bit PPU_STATUS
@1:
    bit PPU_STATUS
    bpl @1

clearRAM:
    txa
@1:
    sta $000,x
    sta $100,x
    sta $200,x
    sta $300,x
    sta $400,x
    sta $500,x
    sta $600,x
    sta $700,x
    inx
    bne @1


waitSync2:
    bit PPU_STATUS
@1:
    bit PPU_STATUS
    bpl @1

	lda #%10000000
	sta <PPU_CTRL_VAR
	sta PPU_CTRL		;enable NMI
	lda #%00000110
	sta <PPU_MASK_VAR

waitSync3:
	lda <FRAMES
@1:
	cmp <FRAMES
	beq @1

;	lda #$fd
;	sta <RAND_SEED
;	sta <RAND_SEED+1

	lda #0
	sta PPU_SCROLL
	sta PPU_SCROLL
